package com.fruit.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fruit.constants.RedisConstant;
import com.fruit.service.redis.UserRedisUtil;
import com.fruit.util.CookieUtil;


public class WapRedisSecurityInterceptor extends HandlerInterceptorAdapter {
	
	@Autowired
	private UserRedisUtil userRedisService;
	

	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		String userToken = CookieUtil.getValue(request, "WAP_USER_TOOKEN");
		String tokenValue = "";
		Integer userId = null;
		if(StringUtils.isNotEmpty(userToken)){	
			if(userRedisService.isExists(RedisConstant.WAP_USER_TOOKEN+userToken)){
				userRedisService.setUserTokenExpire(RedisConstant.WAP_USER_TOOKEN+userToken);
				tokenValue = userRedisService.getUserToken(RedisConstant.WAP_USER_TOOKEN+userToken);
			}	
		}
		String tokenValues[] = StringUtils.split(tokenValue,"_");
		if(tokenValues != null && tokenValues.length != 0){
			userId = Integer.parseInt(tokenValues[0]);
		}
		if(userId != null){
			request.getSession().setAttribute("userId", userId);
		}else{
			request.getSession().removeAttribute("userId");
		}
		
		return true;
	}
}
